import Croppie from 'croppie'
import 'croppie/croppie.css'
import { ref, watch } from 'vue'

export default function useCroppie({
  elementRef,
  sizeRef,
  urlRef,
  setupOptions = {
    viewportType: 'circle',
    showZoomer: true,
    enableOrientation: true,
    minZoom: 1,
    maxZoom: 3,
  },
  resultOptions = {
    type: 'blob',
    size: 'viewport',
    format: 'jpeg',
    quality: 1,
    circle: false,
  },
}) {
  const croppie = ref(null)

  const { viewportType, showZoomer, enableOrientation, minZoom, maxZoom } = setupOptions

  async function init() {
    console.log({ elementRef, sizeRef, urlRef, setupOptions, resultOptions })

    if (!elementRef.value) {
      console.warn('elementRef is not ready')
      return
    }

    if (croppie.value) {
      croppie.value.destroy()
      croppie.value = null
      console.log('Croppie is already initialized, destroy it first')
    }

    croppie.value = new Croppie(elementRef.value, {
      viewport: { width: sizeRef.value, height: sizeRef.value, type: viewportType },
      boundary: { width: sizeRef.value, height: sizeRef.value },
      showZoomer,
      enableOrientation,
      minZoom,
      maxZoom,
    })
    urlRef.value && (await bind(urlRef.value))
    console.log('Croppie initialized')
  }

  const bind = async (url) => {
    await croppie.value.bind({ url })
    console.log('Croppie binded')
  }
  const destory = () => {
    croppie.value.destroy()
    console.log('Croppie destroyed')
  }
  const cut = async () => {
    const r = await croppie.value.result(resultOptions)
    console.log('Croppie cutted')
    return r
  }

  watch(urlRef, async (val) => val && (await bind(val)))
  watch(sizeRef, async (val) => val && (await init()))

  return {
    init,
    cut,
    destory,
  }
}
